package org.keshe.controllers;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.PasswordField;
import org.keshe.CurrentUser;
import org.keshe.gui.PublicStages;

import java.net.URL;
import java.sql.SQLException;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ChangePassWd implements Initializable {

    public Button clear;
    @FXML
    private PasswordField oldPW;

    @FXML
    private PasswordField newPW;

    @FXML
    private PasswordField newPWagain;

    @FXML
    private Button submit;

    private Alert alert1, alert2,
            alert3, alert4, alert5;

    @FXML
    void submitClick(ActionEvent event) {
        String reg = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(newPW.getText());
        if(!matcher.matches()){
            alert1.show();
            return;
        }
        if(!newPW.getText().equals(newPWagain.getText())){
            alert2.show();
            return;
        }
        try {
            if(CurrentUser.USER.changePasswd(oldPW.getText(), newPW.getText())){
                alert3.show();
            }else{
                alert4.show();
            }
        } catch (SQLException e) {
            alert5.show();
            e.printStackTrace();
        }

    }

    public void clearClick() {
        oldPW.setText("");
        newPW.setText("");
        newPWagain.setText("");
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        EventHandler<ActionEvent> clearNewPw = event -> {
            newPW.setText("");
            newPWagain.setText("");
        };
        alert1 = new Alert(Alert.AlertType.ERROR, "密码至少包含 数字和英文，长度6-10", ButtonType.OK);
        Button button = (Button) alert1.getDialogPane().lookupButton(ButtonType.OK);
        button.setOnAction(clearNewPw);
        alert2 = new Alert(Alert.AlertType.ERROR, "新密码两次输入不一致", ButtonType.OK);
        button = (Button) alert2.getDialogPane().lookupButton(ButtonType.OK);
        button.setOnAction(clearNewPw);
        alert3 = new Alert(Alert.AlertType.INFORMATION, "修改成功！", ButtonType.OK);
        button = (Button) alert3.getDialogPane().lookupButton(ButtonType.OK);
        button.setOnAction(e -> {
            clearClick();
            PublicStages.CHANGEPASSWD.close();
        });
        alert4 = new Alert(Alert.AlertType.ERROR, "修改失败，旧密码错误！", ButtonType.OK);
        button = (Button) alert4.getDialogPane().lookupButton(ButtonType.OK);
        button.setOnAction(e -> clearClick());
        alert5 = new Alert(Alert.AlertType.ERROR, "其他错误，数据库连接异常", ButtonType.CLOSE);

    }
}
